<?php

/**
 * Member Admin Controller
 * ระบบ Admin หลักของ Member
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Member Admin system
 * ระบบ admin เพื่อจัดการ member ของเว็บ
 * @package Member
 * @subpackage Controller
 * @category member
 * @author BeYourCyber
 * @version 1.0
 * 
 */
class Admin extends MY_Controller {

    function __construct() {
        parent::MY_Controller();
        $this->load->library('tank_auth');
        $this->load->module('admin');
    }

    /**
     * Index Admin
     * แสดงรายงานเบื้องต้นของ Member
     * 
     */
    function index() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                //นับจำนวนสมาชิกทั้งหมด
                $data['count_all_mem'] = $this->$cl->model->member_m->countAllMem();
                //สมาชิกที่ถูก ban
                $data['count_ban_mem'] = $this->$cl->model->member_m->countBanMem();
                //สมาชิกที่ไม่ active
                $data['count_notactive'] = $this->$cl->model->member_m->countNotactiveMem();
                $this->$cl->view('admin/admin_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Create user
     * สร้าง user ใหม่ผ่านระบบ Admin
     * Confirm หรือไม่ปล่อยให้เป็นการตั้งค่าของระบบ
     * @uses _send_email()
     * @uses Tank_auth::get_error_message()
     */
    function create_user() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        $this->lang->load('tank_auth');
        $this->load->library(array('form_validation'));
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                //บังคับ username หรือเปล่า
                $use_username = $this->config->item('use_username', 'tank_auth');
                if ($use_username) {
                    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $this->config->item('username_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('username_max_length', 'tank_auth') . ']|alpha_dash');
                }
                $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
                $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
                $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');

                $captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
                $use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
                //เปิดใช้ captcha หรือเปล่า
                if ($captcha_registration) {
                    if ($use_recaptcha) {
                        $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
                    } else {
                        $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
                    }
                }
                $data['errors'] = array();

                $email_activation = $this->config->item('email_activation', 'tank_auth');

                if ($this->form_validation->run()) {        // validation ok
                    //สร้าง user ใหม่ได้หรือเปล่า
                    if (!is_null($data = $this->tank_auth->create_user(
                                            $use_username ? $this->form_validation->set_value('username') : '',
                                            $this->form_validation->set_value('email'),
                                            $this->form_validation->set_value('password'),
                                            $email_activation))) {         // success
                        $data['site_name'] = $this->config->item('website_name', 'tank_auth');

                        if ($email_activation) {         // send "activate" email
                            $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

                            $this->_send_email('activate', $data['email'], $data);

                            unset($data['password']); // Clear password (just for any case)

                            $data['complete'] = $this->lang->line('auth_message_registration_completed_1');
                            $this->$cl->view('admin/create_user_complete_v', $data);
                            return;
                        } else {
                            if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
                                $this->_send_email('welcome', $data['email'], $data);
                            }
                            unset($data['password']); // Clear password (just for any case)

                            $data['complete'] = $this->lang->line('auth_message_registration_completed_2');
                            $this->$cl->view('admin/create_user_complete_v', $data);
                            return;
                        }
                    } else {
                        $errors = $this->tank_auth->get_error_message();
                        foreach ($errors as $k => $v)
                            $data['errors'][$k] = $this->lang->line($v);
                    }
                }
                if ($captcha_registration) {
                    if ($use_recaptcha) {
                        $data['recaptcha_html'] = $this->_create_recaptcha();
                    } else {
                        $data['captcha_html'] = $this->_create_captcha();
                    }
                }
                $data['use_username'] = $use_username;
                $data['captcha_registration'] = $captcha_registration;
                $data['use_recaptcha'] = $use_recaptcha;
                $this->$cl->view('admin/create_user_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * All member
     * แสดงสมาชิกทั้งหมด
     *
     * @todo pagination
     * @uses Member_m::getSimpleAllUser()
     */
    function all_member() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {

                //load all member
                $data['member'] = $this->$cl->model->member_m->getSimpleAllUser();
                //load all group
                $data['group'] = $this->$cl->model->group_m->getAllGroup();
                $this->$cl->view('admin/all_member_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * View member detail
     * ดูรายละเอียดของสมาชิก พร้อมทั้งแก้ไขข้อมูล
     * @uses Member_m::getUserId()
     */
    function view_member() {
        $cl = $this->__modulereference;
        $userid = $this->uri->segment(5);
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                //load this member
                $data['member'] = $this->$cl->model->member_m->getUserId($userid);
                unset($data['member']->password); //not use anyway
                //load all group
                $data['group'] = $this->$cl->model->group_m->getAllGroup();
                $this->$cl->view('admin/view_member_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Ban user
     * Ban user โดยกำหนด id และ post เหตุผลมา
     * @param int userid
     * @param string เหตุผล
     * @uses Member_m::ban_user()
     */
    function ban_user() {
        $cl = $this->__modulereference;
        $userid = $this->uri->segment(5);
        $this->$cl->lang('mem');
        $this->load->library('form_validation');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $this->form_validation->set_rules('ban_reason', $this->lang->line('mem.85.banreason'), 'trim|required');
                if (!$userid) {
                    $this->form_validation->set_rules('userid', $this->lang->line('mem.100.userid'), 'trim|required|integer');
                }

                if ($this->form_validation->run()) {
                    //ถ้า get user ไม่ได้ให้รับค่า post มา
                    if (!$userid) {
                        $userid = $this->input->post('userid');
                    }
                    //ban uesr
                    $this->$cl->model->member_m->ban_user($userid, $this->form_validation->set_value('ban_reason'));
                    $data['complete'] = $this->lang->line('mem.101.bancomplete');
                    redirect('member/admin/view_member/' . $userid);
                }
                $this->$cl->load->view('admin/ban_user_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Unban user
     * ปลด ban user
     * @uses Member_m::unban_user();
     */
    function unban_user() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $userid = $this->uri->segment(5);
                if ($userid)
                    $this->$cl->model->member_m->unban_user($userid);
                $destination = htmlspecialchars(getenv("HTTP_REFERER"), ENT_QUOTES, 'UTF-8');
                if (isset($destination{10})) {
                    header("Location: " . $destination);
                }
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Delete member
     * delete member via username
     * @param int userid (uri segment 5)
     */
    function delete_member() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $userid = $this->uri->segment(5);
                if ($userid)
                    $this->$cl->model->member_m->delete_user($userid);
                redirect('member/admin/all_member');
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Activate User by admin
     * @param int userid
     * @uses Member_m::activate_user()
     */
    function activate_user() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $userid = $this->uri->segment(5);
                if ($userid)
                    $this->$cl->model->member_m->activate_user($userid);
                $destination = htmlspecialchars(getenv("HTTP_REFERER"), ENT_QUOTES, 'UTF-8');
                if (isset($destination{10})) {
                    header("Location: " . $destination);
                }
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Search Member
     * ค้นหา member
     * @param string username|email
     * @uses Member_m::get_user_by_login()
     * @uses Member_m::get_user_by_login()
     * @uses Group_m::getAllGroup()
     */
    function search() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $data['login'] = $this->input->post('login');
                $data['member'] = $this->$cl->model->member_m->get_user_by_login($data['login']);
                //load all group
                $data['group'] = $this->$cl->model->group_m->getAllGroup();
                $this->$cl->view('admin/search_member_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Group Index
     * Group management
     * $uses Group_m::getGroupSort()
     */
    function group() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                //load all group
                $data['group'] = $this->$cl->model->group_m->getGroupSort('value');
                $this->$cl->view('admin/group_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Add group
     * Add new group and redirect back
     * @uses Group_m::addGroup()
     * @uses Bee::redirectBack()
     */
    function add_group() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $this->load->library('form_validation');
                $config = array(
                    array(
                        'field' => 'value',
                        'label' => $this->lang->line('member.122.permission'),
                        'rules' => 'required|is_natural_no_zero')
                    , array(
                        'field' => 'group_name',
                        'label' => $this->lang->line('member.124.groupname'),
                        'rules' => 'required|min_length[2]')
                );
                $this->form_validation->set_rules($config);

                if ($this->form_validation->run()) {
                    foreach (explode(' ', 'value group_name') as $v) {
                        $data[$v] = $this->input->post($v);
                    }
                    //add group to database
                    $this->$cl->model->group_m->addGroup($data);
                }
                $this->bee->redirectBack();
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Delete group from id
     * @param int id (get from uri segment 5)
     * @uses Group_m::deleteGroup()
     * @uses Bee::redirectBack()
     */
    function delete_group() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $id = $this->uri->segment(5);
                if ($id) {
                    $this->$cl->model->group_m->deleteGroup($id);
                }
                $this->bee->redirectBack();
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Change user group
     * input user id, member group
     * @param int userid (uri segment 5)
     * @param int memgroup (uri segment 6)
     * @uses Group_m::updateGroupUser()
     */
    function change_group() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $data['id'] = $this->uri->segment(5);

                $data['memgroup'] = $this->uri->segment(6);

                $this->$cl->model->group_m->updateGroupUser($data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * update member profile
     * from member detail page
     * หากมีการเพิ่ม field ใหม่ ให้เพิ่มตัวรับค่าใน function นี้ด้วย(ใน foreach)
     * @param int userid (uri segment 5)
     * @uses Member_m::updateMemberProfile()
     * @uses Bee::redirectBack()
     */
    function change_profile() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $id = $this->uri->segment(5);
                foreach (explode(' ', 'country website') as $v) {
                    $data[$v] = $this->input->post($v);
                }

                $this->$cl->model->member_m->updateMemberProfile($data, $id);
                $this->bee->redirectBack();
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * View member in group
     * @param int group value (uri segment 5)
     * @uses Group_m::getGroupNameFromValue()
     * @uses Member_m::getMemberGroup()
     */
    function view_group_member() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $id = $this->uri->segment(5);
                if ($id != 120 AND $id != 30) {
                    //get group name
                    $data['group_name'] = $this->$cl->model->group_m->getGroupNameFromValue($id);
                    //get member in this group
                    $data['member'] = $this->$cl->model->member_m->getMemberGroup($id);
                    $this->$cl->view('admin/view_group_member_v', $data);
                }
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * reset password for admin
     * สำหรับ admin reset password และส่งเมล activate เพื่อให้คลิกและตั้งรหัสผ่านใหม่
     * @param int userid
     * @uses _send_email()
     * @uses Member_m::getUserId()
     * @uses Tank_auth::forgot_password()
     */
    function reset_password() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $id = $this->uri->segment(5);
                //get username from id
                $user = $this->$cl->model->member_m->getUserId($id);
                $this->lang->load('tank_auth');
                if (!is_null($data = $this->tank_auth->forgot_password(
                                        $user->username))) {

                    $data['site_name'] = $this->config->item('website_name', 'tank_auth');

                    // Send email with password activation link
                    $this->_send_email('forgot_password', $data['email'], $data);

                    echo $this->lang->line('auth_message_new_password_sent');
                    return;
                } else {
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * หน้าค้นหาสมาชิก เพื่อจัดการคะแนน
     *
     *
     */
    function point() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                //load คะแนนของสมาชิกทุกคน
                $data['allscore'] = $this->$cl->model->score_m->load_sum_member_score();

                $this->$cl->view('admin/point_index_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * View member and karma of this member
     * @param $userid uri->segment(5)
     * @uses Member_m::getUserId()
     * @uses Score_m::load_score()
     * @uses Score_m::load_log()
     */
    function view_point() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $userid = $this->uri->segment(5);
                //load this member
                $data['member'] = $this->$cl->model->member_m->getUserId($userid);
                //load member point
                $data['member_score'] = $this->$cl->model->score_m->load_score($userid, $type = 'score');
                //load member karma
                $data['member_karma'] = $this->$cl->model->score_m->load_score($userid, $type = 'karma');
                //load member log point
                $data['member_log_point'] = $this->$cl->model->score_m->load_log($userid, 20, 0, 'DESC', $type = 'score');
                //load member log karma
                $data['member_log_karma'] = $this->$cl->model->score_m->load_log($userid, 20, 0, 'DESC', $type = 'karma');
                $this->$cl->view('admin/view_point_v', $data);
            }
        } else {
            redirect('');
        }
    }

    /**
     * AJAX load point
     * for ajax load point only not open windows
     * @uses Score_m::load_log()
     * @uses Score_m::countScoreUser()
     */
    function load_point() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $this->load->library('pagination');
                $userid = $this->uri->segment(5);
                $type = $this->uri->segment(6);

                $data['countmember'] = $this->$cl->model->score_m->countScoreUser($userid, $type);
                $data['perpage'] = 20;
                $data['uri_segment'] = 7;
                //load log point of this member
                if ($this->uri->segment($data['uri_segment']) && preg_match('/^[0-9]+$/', $this->uri->segment($data['uri_segment']))) {
                    $page = $this->uri->segment($data['uri_segment']);
                    $data['member_log_point'] = $this->$cl->model->score_m->load_log($userid, $data['perpage'], $page, 'DESC', $type);
                } else {
                    $data['member_log_point'] = $this->$cl->model->score_m->load_log($userid, $data['perpage'], 0, 'DESC', $type);
                }
                $this->$cl->view('admin/load_point_v', $data);
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    function take_score() {
        $cl = $this->__modulereference;
        $this->$cl->lang('mem');
        if ($this->tank_auth->is_logged_in()) {
            //check admin
            if ($this->tank_auth->is_admin()) {
                $this->load->library('pagination');
                $userid = $this->uri->segment(5);
                $type = $this->uri->segment(6);
                $this->load->library('form_validation');
                $config = array(
                    array(
                        'field' => 'point',
                        'label' => 'point',
                        'rules' => 'required|min_length[2]|max_length[4]|integer')
                    ,array(
                        'field' => 'reason',
                        'label' => 'reason',
                        'rules' => 'required|min_length[3]|max_length[240]')
                );
                $this->form_validation->set_rules($config);

                if ($this->form_validation->run() == FALSE) {
                    echo 'please input data';
                } else {
                    //เพิ่ม หรือ ลดคะแนน
                    $this->$cl->model->score_m->take_score($userid,$this->input->post('point'),$this->input->post('reason'),$type);
                    redirect('member/admin/view_point/' . $userid);
                }
                
            } else {
                header('Content-type: text/html; charset=utf-8');
                echo $this->lang->line('admin_system.not_permission');
            }
        } else {
            redirect('');
        }
    }

    /**
     * Send email message of given type (activate, forgot_password, etc.)
     *
     * @param	string
     * @param	string
     * @param	array
     * @return	void
     */
    function _send_email($type, $email, &$data) {
        $this->load->module('theme');
        $current_theme = $this->theme->library->theme_lib->get_theme();
        $this->load->library('email');
        $this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
        $this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
        $this->email->to($email);
        $this->email->subject(sprintf($this->lang->line('auth_subject_' . $type), $this->config->item('website_name', 'tank_auth')));
        $this->email->message($this->theme->view($current_theme . '/auth/email/' . $type . '-html', $data, TRUE));
        $this->email->set_alt_message($this->theme->view($current_theme . '/auth/email/' . $type . '-txt', $data, TRUE));
        $this->email->send();
    }

    /**
     * Create CAPTCHA image to verify user as a human
     *
     * @return	string
     */
    function _create_captcha() {

        $cap = '<img src="/captcha/show/' . sha1($_SERVER['REMOTE_ADDR'] . rand(0, 1000) . time()) . '.png" id="siimage" />
            <a tabindex="-1" style="border-style: none" href="' . current_url() . '#" title="Refresh Image" onclick="document.getElementById(\'siimage\').src = \'/captcha/show/\' + Math.random(); return false">reload</a>';

        return $cap;
    }

    /**
     * Callback function. Check if CAPTCHA test is passed.
     *
     * @param	string
     * @return	bool
     */
    function _check_captcha($code) {
//        $time = $this->session->flashdata('captcha_time');
//        $word = $this->session->flashdata('captcha_word');
//
//        list($usec, $sec) = explode(" ", microtime());
//        $now = ((float) $usec + (float) $sec);
//
//        if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) {
//            $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
//            return FALSE;
//        } elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') AND
//                $code != $word) OR
//                strtolower($code) != strtolower($word)) {
//            $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
//            return FALSE;
//        }
//        return TRUE;
        $this->load->library('Securimage');
        if (!$this->securimage->check($code)) {
            $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /**
     * Create reCAPTCHA JS and non-JS HTML to verify user as a human
     *
     * @return	string
     */
    function _create_recaptcha() {
        $this->load->helper('recaptcha');

        // Add custom theme so we can get only image
        $options = "<script>var RecaptchaOptions = {theme: 'custom', custom_theme_widget: 'recaptcha_widget'};</script>\n";

        // Get reCAPTCHA JS and non-JS HTML
        $html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

        return $options . $html;
    }

    /**
     * Callback function. Check if reCAPTCHA test is passed.
     *
     * @return	bool
     */
    function _check_recaptcha() {
        $this->load->helper('recaptcha');

        $resp = recaptcha_check_answer($this->config->item('recaptcha_private_key', 'tank_auth'),
                        $_SERVER['REMOTE_ADDR'],
                        $_POST['recaptcha_challenge_field'],
                        $_POST['recaptcha_response_field']);

        if (!$resp->is_valid) {
            $this->form_validation->set_message('_check_recaptcha', $this->lang->line('auth_incorrect_captcha'));
            return FALSE;
        }
        return TRUE;
    }

}
